package com.t168.appinfo.controller.reception;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.mysql.jdbc.log.LogUtils;
import com.t168.appinfo.entity.AppCategory;
import com.t168.appinfo.entity.AppInfo;
import com.t168.appinfo.entity.AppVersion;
import com.t168.appinfo.entity.DevUser;
import com.t168.appinfo.entity.Dictionary;
import com.t168.appinfo.entity.PageSupport;
import com.t168.appinfo.service.background.appversion.BgAppVersionService;
import com.t168.appinfo.service.reception.Dictionary.DictionaryService;
import com.t168.appinfo.service.reception.appcategory.AppCategoryService;
import com.t168.appinfo.service.reception.appinfo.AppInfoService;
import com.t168.appinfo.service.reception.appversion.AppVersionService;

@Controller
@RequestMapping("/appInfo")
public class AppInfoController {

	private Logger logger = Logger.getLogger(AppInfoController.class);
	
	@Resource(name = "appInfoService")
	private AppInfoService appInfoService;
	
	@Resource(name = "appCategoryService")
	private AppCategoryService appCategoryService;
	
	@Resource(name = "dictionaryService")
	private DictionaryService dictionaryService;
	
	
	@Resource(name = "appVersionService")
	private AppVersionService appVersionService;
	public AppVersionService getAppVersionService() {
		return appVersionService;
	}

	public void setAppVersionService(AppVersionService appVersionService) {
		this.appVersionService = appVersionService;
	}

	public DictionaryService getDictionaryService() {
		return dictionaryService;
	}

	public void setDictionaryService(DictionaryService dictionaryService) {
		this.dictionaryService = dictionaryService;
	}

	public AppCategoryService getAppCategoryService() {
		return appCategoryService;
	}

	public void setAppCategoryService(AppCategoryService appCategoryService) {
		this.appCategoryService = appCategoryService;
	}

	public AppInfoService getAppInfoService() {
		return appInfoService;
	}

	public void setAppInfoService(AppInfoService appInfoService) {
		this.appInfoService = appInfoService;
	}
	
	
	
	@RequestMapping(value="/addInfo.html")
	public String addInfoView(){
		return "jsp/developer/appinfoadd";
	}
	
	
	
	
	@RequestMapping(value = "/appinfoaddsave")
	public String addInfo(@ModelAttribute("appInfo") AppInfo appInfo,@RequestParam(value ="a_logoPicPath", required = false) MultipartFile attach,HttpSession session,HttpServletRequest request){
		String idPicPath = null;
		String logoPicPath = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
			//定义上传的目标路径
			//String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
			String path = "E:\\workspace\\AppInfoSystem\\WebContent\\statics\\uploadfiles";
			logger.info("uploadFile path ============== > "+path);
			//获取原文件名
			String oldFileName = attach.getOriginalFilename();
			logger.info("uploadFile oldFileName ==============> "+oldFileName);
			System.out.println(File.separator);
			//获取原文件名的后缀
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        logger.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			
			logger.debug("uploadFile size============> " + attach.getSize());
			//上传大小不得超过 500k
	        if(attach.getSize() >  filesize){
            	request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
	        	return "jsp/developer/appinfoadd";
	        	
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")|| prefix.equalsIgnoreCase("png") 
            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
            	//新的照片名称，毫秒数加随机数，确保不能重复
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg"; 
            	logoPicPath = "statics/uploadfiles/"+fileName;
                logger.debug("new fileName======== " + attach.getName());
                //创建文件对象，此文件对象用于接收用户上传的文件流
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	//把MultipartFile中的文件流数据的数据输出至目标文件中
                	attach.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadFileError", " * 上传失败！");
                    return "jsp/developer/appinfoadd";
                }
                //获取文件的的名称保存到数据库中
                idPicPath = path+File.separator+fileName;
            }else{
            	request.setAttribute("uploadFileError", " * 上传图片格式不正确");
            	return "jsp/developer/appinfoadd";
            }
		}
		
		appInfo.setLogoPicPath(logoPicPath);
		appInfo.setCreatedBy(((DevUser)session.getAttribute("devUser")).getId());
		appInfo.setCreationDate(new Date());
		//把文件名称写入到对象里面
		appInfo.setLogoLocPath(idPicPath);
		
		
		
		if(appInfoService.addAppInfo(appInfo)){
			return "redirect:/appInfo/appInfolist.html";
		}else{
			request.setAttribute("uploadFileError", " * 上传图片格式不正确");
			return "jsp/developer/appinfoadd";
		}
	}


	@RequestMapping(value = "/appInfolist.html")
	public String appInfo(
			@RequestParam(value="queryCategoryLevel1",required = false) String level1,
			@RequestParam(value="queryCategoryLevel2",required = false) String level2,
			@RequestParam(value="queryCategoryLevel3",required = false) String level3,
			@RequestParam(value="querySoftwareName",required = false) String softwareName,
			@RequestParam(value="queryFlatformId",required = false) String flatformId,
			@RequestParam(value="queryStatus",required = false) String state,
			@RequestParam(value="pageIndex",required = false) String pageIndex,
			HttpServletRequest request){
		//创建页面类对象
		PageSupport pageSupport = new PageSupport();
		
		if(null == pageIndex || "".equals(pageIndex)){
			pageIndex = "1";
		}
		
		int pageCount = 5;
		pageSupport.setPageSize(pageCount);
		int totalCount = appInfoService.getAppInfoCount(level1, level2, level3, softwareName, flatformId,state);
		pageSupport.setTotalCount(totalCount);
		if(Integer.valueOf(pageIndex).intValue() > pageSupport.getTotalPageCount()){
			pageIndex = "1";
		}
		
		List<Dictionary> flatFromList = dictionaryService.getFlatFrom();
		List<Dictionary> status = dictionaryService.getStatus();
		List<AppCategory> appcategorys = appCategoryService.getLevelOneCgInfo();

		if(level1 != null && !"".equals(level1)){
			List<AppCategory> levelTwos = appCategoryService.getLevelTwoCgInfo(level1);
			System.out.println("levelTwos.size()"+levelTwos.size());
			request.setAttribute("levelTwos", levelTwos);
		}
		
		if(level2 != null &&! "".equals(level2)){
			List<AppCategory> levelThrees = appCategoryService.getLevelThreeCgInfo(level2);
			System.out.println("levelThrees.size()"+levelThrees.size());
			request.setAttribute("levelThrees", levelThrees);
		}
		List<AppInfo> appInfoList = appInfoService.getAppInfo(level1, level2, level3, softwareName,  flatformId,state,Integer.valueOf(pageIndex).intValue(),pageCount );
		AppInfoController.pageIndex = pageIndex;
		AppInfoController.pageSize = pageCount;
		AppInfoController.totalCount = totalCount;
		request.setAttribute("flatFromList", flatFromList);
		request.setAttribute("status", status);
		request.setAttribute("appcategorys", appcategorys);
		request.setAttribute("appInfoList", appInfoList);
		request.setAttribute("pageIndex", pageIndex);
		request.setAttribute("totalPageCount", pageSupport.getTotalPageCount());
		request.setAttribute("totalCount", totalCount);
		request.setAttribute("totalPageCount", pageSupport.getTotalPageCount());
		request.setAttribute("softwareName", softwareName);
		request.setAttribute("level1", level1);
		request.setAttribute("level2", level2);
		request.setAttribute("level3", level3);
		request.setAttribute("flatformId", flatformId);
		request.setAttribute("state", state);
		return "jsp/developer/appinfolist";
	}
	
	
	
	@RequestMapping("/apkExist")
	@ResponseBody
	public String apkExist(String apkName){
		if(apkName == null || "".equals(apkName)){
			return "empty";
		}
		if(appInfoService.apkExist(apkName)){
			return "exist";
		}else{
			return "noexist";
		}
	}
	
	@RequestMapping("/appInfoView.html")
	public String appInfoView(@RequestParam("appInfoId")String appInfoId,HttpServletRequest request){
		AppInfo appInfo = appInfoService.getAppInfoViewById(Integer.valueOf(appInfoId).intValue());
		request.setAttribute("appInfo", appInfo);
		AppInfo appInfoVersions = appInfoService.historyVersion(Integer.valueOf(appInfoId).intValue());
		System.out.println(appInfo.getLogoLocPath());
		request.setAttribute("appInfoVersions", appInfoVersions);
		return "jsp/developer/appinfoview";
	}
	
	
	@RequestMapping(value = "/modifyAppInfoView.html")
	public String modifyAppInfoView(
			@RequestParam("appInfoId")String appInfoId,
			HttpServletRequest request){
		AppInfo appInfo = appInfoService.getAppInfoViewById(Integer.valueOf(appInfoId).intValue());
		request.setAttribute("appInfo", appInfo);
		List<Dictionary> flatForms = dictionaryService.getFlatFrom();
		List<AppCategory> categorys = appCategoryService.getLevelOneCgInfo();
		List<AppCategory> categoryTwo = appCategoryService.getLevelTwoCgInfo(appInfo.getCategoryLevel1().toString());
		List<AppCategory> categoryThree = appCategoryService.getLevelTwoCgInfo(appInfo.getCategoryLevel2().toString());
		request.setAttribute("categorys", categorys);
		request.setAttribute("flatForms", flatForms);
		request.setAttribute("categoryTwo", categoryTwo);
		request.setAttribute("categoryThree", categoryThree);
		return "jsp/developer/appinfomodify";
	}
	
	@RequestMapping("/appinfomodifysave")
	public String appinfomodifysave(@ModelAttribute("appInfo")AppInfo appInfo,@RequestParam(value ="attach", required = false) MultipartFile attach,HttpServletRequest request,HttpSession session){
		String idPicPath = null;
		String logoPicPath = null;
		//判断文件是否为空
		if(!attach.isEmpty()){
			//定义上传的目标路径
			//String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
			String path = "E:\\workspace\\AppInfoSystem\\WebContent\\statics\\uploadfiles";
			logger.info("uploadFile path ============== > "+path);
			//获取原文件名
			String oldFileName = attach.getOriginalFilename();
			logger.info("uploadFile oldFileName ==============> "+oldFileName);
			System.out.println(File.separator);
			//获取原文件名的后缀
			String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
	        logger.debug("uploadFile prefix============> " + prefix);
			int filesize = 500000;
			
			logger.debug("uploadFile size============> " + attach.getSize());
			//上传大小不得超过 500k
	        if(attach.getSize() >  filesize){
            	request.setAttribute("uploadFileError", " * 上传大小不得超过 500k");
				return "redirect:/appInfo/modifyAppInfoView.html?appInfoId="+appInfo.getId();
	        	
            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")|| prefix.equalsIgnoreCase("png") 
            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
            	//新的照片名称，毫秒数加随机数，确保不能重复
            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg"; 
            	logoPicPath = "statics/uploadfiles/"+fileName;
                logger.debug("new fileName======== " + attach.getName());
                //创建文件对象，此文件对象用于接收用户上传的文件流
                File targetFile = new File(path, fileName);  
                if(!targetFile.exists()){  
                    targetFile.mkdirs();  
                }  
                //保存  
                try {  
                	//把MultipartFile中的文件流数据的数据输出至目标文件中
                	attach.transferTo(targetFile);  
                } catch (Exception e) {  
                    e.printStackTrace();  
                    request.setAttribute("uploadFileError", " * 上传失败！");
        			return "redirect:/appInfo/modifyAppInfoView.html?appInfoId="+appInfo.getId();
                }
                //获取文件的的名称保存到数据库中
                idPicPath = path+File.separator+fileName;
                
                appInfo.setLogoPicPath(logoPicPath);
        		appInfo.setLogoLocPath(idPicPath);
            }else{
            	request.setAttribute("uploadFileError", " * 上传图片格式不正确");
    			return "redirect:/appInfo/modifyAppInfoView.html?appInfoId="+appInfo.getId();
            }
		}
		
		appInfo.setModifyBy(((DevUser)session.getAttribute("devUser")).getId());
		appInfo.setModifyDate(new Date());
		if(appInfoService.modifyAppInfoSave(appInfo)){
			return "redirect:/appInfo/appInfolist.html";
		}else{
			request.setAttribute("uploadFileError", " * 修改失败");
			return "redirect:/appInfo/modifyAppInfoView.html?appInfoId="+appInfo.getId();
		}
	}
	
	@RequestMapping(value = "/delAppInfoById")
	@ResponseBody
	public String delAppInfoById(@RequestParam("appId")String appId){
		AppInfo appInfo = appInfoService.getAppInfoViewById(Integer.valueOf(appId).intValue());
		AppInfo appInfoVersions = appInfoService.historyVersion(Integer.valueOf(appId).intValue());
		if (appInfoVersions != null
				&& appInfoVersions.getAppVersionList() != null
				&& appInfoVersions.getAppVersionList().size() > 0) {
			for (AppVersion version : appInfoVersions.getAppVersionList()) {
				if (version.getApkLocPath() != null) {
					File file = new File(version.getApkLocPath());
					/*
					 * the delete() method return true if the file deleted
					 * successfully else it return false
					 */
					if (file.delete()) {
						logger.info(file.getName() + "is deleted");
					} else {
						logger.info("Delete failed.");
					}
				}
			}
		}

		if (appInfo.getLogoLocPath() != null) {
			File file = new File(appInfo.getLogoLocPath());

			if (file.delete()) {
				logger.info(file.getName() + "LOGO is deleted");
			} else {
				logger.info("LOGO Delete failed.");
			}
		}
		
		
		String flag = "false";
		appVersionService.delAppVersion(Integer.valueOf(appId).intValue());
		if(appInfoService.delAppInfoById(Integer.valueOf(appId).intValue())){
			flag = "true";
		}
		return flag;
	}
	
	@RequestMapping(value="/modifyAppInfoStatus",method=RequestMethod.GET)
	@ResponseBody
	public String modifyAppInfoStatus(@RequestParam("id")int id,@RequestParam("saleSwitch")String saleSwitch){
		String resultMsg = "failed";
		String errorCode = "0";
		try{
			if (appInfoService.modifyAppInfoStatus(id, saleSwitch)) {
			resultMsg ="success";
			}
		}catch(Exception e){
			errorCode = "1";
			e.printStackTrace();
		
		}
		
		Map<String, String> data = new HashMap<String,String>();
		data.put("resultMsg", resultMsg);
		data.put("errorCode", errorCode);
		return JSON.toJSONString(data);
	}
	
		//当前页面
		private static String pageIndex;
		//当前总记录
		private static int totalCount;
		//当前每页展示的条数
		private static int pageSize;
	
		
	@RequestMapping(value = "/pageInfo")
	@ResponseBody
	public Object pageInfo(){
		Map<String, String> map = new HashMap<String, String>();
		AppInfoController.totalCount--;
		int totalPageCount = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
		map.put("pageIndex", AppInfoController.pageIndex);
		map.put("totalCount",String.valueOf(totalCount));
		map.put("totalPageCount", String.valueOf(totalPageCount));
		return JSON.toJSONString(map);
	}
	
	
	
	

	
}
